<template>
  <div class="page-box">
    <el-form :inline="true" :model="searchData" ref="form" label-width="110px">

      <el-form-item label="采购单位">
        <el-input v-model="searchData.buyingUnit" placeholder="请输入采购单位" ></el-input>
      </el-form-item>
      <el-form-item label="供应商订单号">
        <el-input v-model="searchData.orderNo" placeholder="请输入订单号" ></el-input>
      </el-form-item>
      <el-form-item label="下单起始时间">
        <el-date-picker v-model="searchData.orderStartTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
      </el-form-item>
      <el-form-item label="下单结束时间">
        <el-date-picker v-model="searchData.orderEndTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
      </el-form-item>
      <el-form-item >
        <el-button type="primary" icon="el-icon-search" @click="handleCurrentChange(1)">查询</el-button>
      </el-form-item>
    </el-form>

    <el-row class="page-box-tool">
      <el-button type="success" @click="openSync()">导入对账单</el-button>
    </el-row>

    <el-table
        border
        :data="tableData"
        :max-height="maxHeightNow"
        style="width: 100%"
        >
      <el-table-column prop="orderShowId" fixed label="总订单号"  width="130px"></el-table-column>
      <el-table-column prop="supplierOrderNo" fixed label="供应商订单号"  width="130px"></el-table-column>
      <el-table-column prop="goodsSku"  label="sku"  width="120px"></el-table-column>
      <el-table-column prop="buyingUnit" label="采购单位"  minWidth="200px"></el-table-column>
      <el-table-column prop="goodsName"  label="商品名称"  width="320px"></el-table-column>
      <el-table-column prop="supPrice"  label="含税单价"  width="110px"></el-table-column>
      <el-table-column prop="excludeTaxPrice"  label="未税单价"  width="110px"></el-table-column>
      <el-table-column prop="quantity"  label="数量"  width="110px"></el-table-column>
      <el-table-column prop="eshopOrderPrice"  label="含税总价"  width="110px"></el-table-column>
      <el-table-column prop="sumExcludeTaxPrice"  label="未税总价"  width="110px"></el-table-column>
      <el-table-column prop="orderTime"  label="下单日期"  width="190px"></el-table-column>
      <el-table-column prop="reconciliationRemark" label="备注"  minWidth="200px"></el-table-column>
      <el-table-column prop="reconciliationStatusValue"  label="对账状态"  width="120px" fixed="right"></el-table-column>
    </el-table>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size=pageSize
        layout="total, sizes, prev, pager, next, jumper"
        :total=totalPage>
    </el-pagination>

    <el-dialog title="导入对账单" :visible.sync="dialogExcelVisible" width="40%">
      <el-upload
        class="upload-demo"
        ref="upload"
        :action="uploadUrl"
        :headers="myHeader"
        accept=".xlsx"
        :limit="1"
        :file-list="fileList"
        :on-change="onChange"
        :auto-upload="false"
        :before-remove="beforeRemove"
        :on-success="onUploadSuc"
        :on-error="onUploadErr"
        :on-exceed="handleExceed">
        <el-button slot="trigger" size="small" type="primary">选取本地文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        <el-link icon="el-icon-download" target='_blank' style="float:right; margin-right:25px;" type="primary" @click="downExcel()">下载对账单模板</el-link>
        <div slot="tip" class="el-upload__tip">只能上传一个Excel文件(*.xlsx)，且不超过2Mb</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogExcelVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import { reconciliationCreat, exportReconciliation} from '@/api/supplier.api';
  import moment from 'moment'
  import fileUpdata from '@/api/file.config'
  export default {
    name: 'reconciliation-localmall',
    components: {},
    data() {
      return {
        searchData:{
        },
        purchaseList:[],

        tableData:[],
        currentPage:1,
        pageSize:10,
        totalPage:0,

        dialogExcelVisible:false,
        uploadUrl:'/api/order/reconciliation/localImport',
        myHeader:'',
        fileList:[], //上传文件列表
        canUpload:false,

      }
    },
    watch: {},
    computed: {
      maxHeightNow () {
        const height = window.innerHeight
        return height -  320
      }
    },
    filters: {
      formeTime(val){
        return val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : ' '
      }
    },
    created() {
      this.onSearch();
    },
    mounted() {
      this.myHeader = {...fileUpdata.headers()}
    },
    methods: {
      onSearch(){
        this.searchData.current = this.currentPage;
        this.searchData.size = this.pageSize;

        reconciliationCreat(this.searchData).then( res =>{
          this.tableData = res.records
          this.totalPage = res.total
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.currentPage = 1
        this.onSearch()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.onSearch()
      },

      openSync(){
        this.dialogExcelVisible = true
      },
      submitUpload(){
        if(!this.canUpload){
          this.$message({
            message: '请选择需上传的文件',
            type: 'warning'
          });
          return
        }
        this.$refs.upload.submit()
      },
      onChange(file, fileList){
      this.canUpload=false;
      var testmsg=file.name.substring(file.name.lastIndexOf('.')+1)
      const extension = testmsg === 'xlsx'
      if(!extension){
        this.$message({
          message: '只可上传Excel文件(*.xlsx)',
          type: 'warning'
        });
        this.$refs.upload.clearFiles();
        return;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if(!isLt2M){
        this.$message({
          message: '文件大小不可超过2MB)',
          type: 'warning'
        });
        this.$refs.upload.clearFiles();
        return;
      }
      if(fileList.length>0){
        this.canUpload=true;
      }
      },
      // 提交检测判断
      handleExceed(files, fileList) {
        this.$message.warning(`最多可上传 1 个附件，您已超限`)
      },
      beforeRemove(){
        this.canUpload=false;
      },
      onUploadSuc(response, file, fileList){
      const data = response;
      if (data.code === 0) {
        this.$message({
          message: "导入成功",
          type: "success"
        });
        this.canUpload=false;
        this.$refs.upload.clearFiles();
        this.dialogExcelVisible=false;
        this.onSearch();
      } else {
        this.$message.error(data.msg);
        this.canUpload=false;
        this.$refs.upload.clearFiles();
      }

      },

      onUploadErr(err){
        let errBody = err.message
        if (errBody) {
          errBody = JSON.parse(errBody)
          this.$message({
            type: 'error',
            message: errBody&&errBody.msg
          })
          this.$message.error(err.msg)
        }
      },
      downExcel(){
        exportReconciliation().then((res) => {
          let blob = new Blob([res], { type: "application/vnd.ms-excel" });
          this.saveAs(blob, "对账单录入模板.xlsx");
        });
      },
      saveAs(blob, filename) {
        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, filename);
        } else {
          var link = document.createElement("a");
          var body = document.querySelector("body");
          link.href = window.URL.createObjectURL(blob);
          link.download = filename;
          link.style.display = "none";
          body.appendChild(link);
          link.click();
          body.removeChild(link);
          window.URL.revokeObjectURL(link.href);
        }
      },



    }
  }
</script>

<style scoped lang="scss">
  .page-box {
    padding: 20px;
    background: white;
    .form-operation {
      text-align: right;
      .el-form-item {
        margin-right: 0;
      }
    }
    .el-pagination {
      padding: 20px;
      text-align: right;
    }
    &-tool {
      // text-align: right;
      padding-bottom: 20px;
    }
  }

</style>
